import {
    Information
} from './information.model'
import {
    Area
} from '../../utils/area'
import {
    Config
} from '../../utils/config'
import Toast from '@vant/weapp/toast/toast'
const information = new Information()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: '', // 个人信息
        areaList: '', // 地区列表
        showGenderPopup: false, // 显示性别面板
        showDatePopup: false, // 显示日期面板
        showAreaPopup: false, // 显示地区面板
        minDate: new Date(1900, 0, 1).getTime(), // 可选最早日期
        maxDate: new Date().getTime(), // 可选最晚日期
        currentGender: 1, // 当前性别
        currentSex: '男', // 当前性别
        currentAddress: '', // 当前地址
        currentProvinceId: '', // 当前省份ID
        currentCityId: '', // 当前城市ID
        currentBirthday: 0, // 当前日期
        currentDate: 0, // 当前日期
        // 格式化日期选择器文字
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            return value
        },
        errMsg: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        let that = this
        that._loadData()
    },

    /**
     * 获取所有数据
     */
    _loadData() {
        let that = this
        // 是否授权
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    that.getUserData()
                    that.getAreaData()
                }
            }
        })
    },

    /**
     * 获取用户数据
     */
    getUserData() {
        wx.showLoading({
            title: '正在加载数据',
        })
        let that = this
        const userInfo = information.getStorage('userInfo')
        if (userInfo) {
            that.setData({
                userInfo: userInfo,
                currentGender: userInfo.gender,
                currentSex: userInfo.sex,
                currentAddress: userInfo.address,
                currentProvinceId: userInfo.province_id,
                currentCityId: userInfo.city_id,
                currentBirthday: userInfo.birthday,
                currentDate: new Date(userInfo.birthday).getTime()
            })
        } else {
            information.getUserData().then((res) => {
                information.setStorage('userInfo', res.data)
                that.setData({
                    userInfo: res.data,
                    currentGender: res.data.gender,
                    currentSex: userInfo.sex,
                    currentAddress: userInfo.address,
                    currentProvinceId: userInfo.province_id,
                    currentCityId: userInfo.city_id,
                    currentBirthday: userInfo.birthday,
                    currentDate: new Date(userInfo.birthday).getTime()
                })
            })
        }
        wx.hideLoading()
    },

    /**
     * 获取省市数据
     */
    getAreaData() {
        let that = this
        const areaList = information.getStorage('areaList')
        if (areaList) {
            that.setData({
                areaList: areaList
            })
        } else {
            const areaList = {
                province_list: Area.province_list,
                city_list: Area.city_list
            }
            information.setStorage('areaList', areaList)
            that.setData({
                areaList: areaList
            })
        }
    },

    /**
     * 解密消息, 获取用户手机号
     * @param {*} options
     */
    onGetPhoneNumber(options) {
        if (options.detail.errMsg == "getPhoneNumber:ok") {
            let that = this,
                param = {
                    encryptedData: options.detail.encryptedData,
                    iv: options.detail.iv
                }
            information.getUserPhoneData(param).then((res) => {
                let userInfo = that.data.userInfo
                userInfo.phone = res.data.phoneNumber
                that.setData({
                    userInfo: userInfo
                })
            })
        }
    },

    /**
     * 修改性别
     */
    onTapGender() {
        this.setData({
            showGenderPopup: true
        })
    },

    /**
     * 选择性别
     * @param {*} options
     */
    onChooseGender(options) {
        let that = this,
            gender = information.getDataSet(options, 'gender'),
            sex = information.getDataSet(options, 'sex')
        that.setData({
            currentSex: sex,
            currentGender: gender,
            showGenderPopup: false
        })
    },

    /**
     * 修改生日
     */
    onTapBirthday() {
        this.setData({
            showDatePopup: true
        })
    },

    /**
     * 确认日期选择
     * @param {*} options
     */
    onChooseDate(options) {
        let that = this,
            date = information.getFullDate(options.detail)
        that.setData({
            currentBirthday: date,
            currentDate: options.detail,
            showDatePopup: false
        })
    },

    /**
     * 修改地址
     */
    onTapAddress() {
        this.setData({
            showAreaPopup: true
        })
    },

    /**
     * 确认选择省市
     * @param {*} options
     */
    onChooseArea(options) {
        let that = this,
            area = options.detail.values
        that.setData({
            currentAddress: `${area[0].name} / ${area[1].name}`,
            currentProvinceId: area[0].code,
            currentCityId: area[1].code,
            showAreaPopup: false,
        })
    },

    /**
     * 关闭弹出层
     */
    onClosePopup() {
        this.setData({
            showGenderPopup: false,
            showDatePopup: false,
            showAreaPopup: false
        })
    },

    /**
     * 提交数据
     * @param {*} options
     */
    doSubmit(options) {
        let that = this,
            userInfo = options.detail.value,
            errMsg = ''
        userInfo.nick_name = userInfo.nick_name.trim()
        if (!userInfo.nick_name) {
            errMsg = '昵称不能为空'
        }
        if (userInfo.email && !Config.email.test(userInfo.email)) {
            errMsg = '邮箱格式不正确'
        }
        if (errMsg) {
            Toast(errMsg)
            return false
        }
        if (!userInfo.birthday) {
            delete userInfo.birthday
        }
        that.updateUserData(userInfo)
    },

    /**
     * 将数据更新到服务器
     * @param {*} userInfo
     */
    updateUserData(userInfo) {
        information.updateUserData(userInfo).then((res) => {
            information.setStorage('userInfo', res.data)
            Toast({
                type: 'success',
                message: '修改成功',
                onClose: () => {
                    let prevPage = information.getPrevPage() // 获取上一页
                    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
                    prevPage.setData({
                        userInfo: res.data,
                    })
                    wx.navigateBack({
                        delta: 1,
                    })
                },
            })
        })
    }
})